<script lang="ts" setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// import { useLoad } from '@tarojs/taro'

import VEmpty from './Empty/index.vue'

interface Props {
  // eslint-disable-next-line @typescript-eslint/ban-types
  request: Function
  pageSize?: number
}

const props = withDefaults(defineProps<Props>(), {
  pageSize: 20,
})

const emit = defineEmits<{
  'fetch:done': []
}>()

const listData = ref<any>([])

const total = ref<number>()
const isBusinessError = ref(false)

const loading = ref(false)

const params = {
  pageNum: 1,
  pageSize: 20,
}

onLoad(() => {
  fetchData()
})

const triggered = ref(false)

async function fetchData() {
  if (params.pageNum === 1) {
    triggered.value = true
  }
  loading.value = true

  try {
    const { total: _total = 0, rows: _rows } = await props.request({
      ...params,
      pageSize: props.pageSize,
    })

    isBusinessError.value = false
    total.value = _total || 0
    listData.value.push(...(_rows || []))
  } catch (error) {
    console.error(error)
    total.value = 0
    isBusinessError.value = true
  }

  loading.value = false
  triggered.value = false
  emit('fetch:done')
}

function onUpper(e) {
  params.pageNum = 1
  listData.value = []
  fetchData()
}

function onLower(e) {
  console.log('lower:', e)

  if (total.value === (listData.value || []).length) {
    return
  }

  params.pageNum += 1
  fetchData()
}

defineExpose({
  refresh: onUpper,
})
</script>

<template>
  <!-- @scrolltoupper="onUpper" -->
  <view class="scroll-list-view">
    <scroll-view
      :scroll-y="true"
      :refresher-enabled="true"
      :refresher-triggered="triggered"
      style="height: 100%"
      @refresherRefresh="onUpper"
      @scrolltolower="onLower"
    >
      <view v-for="(item, index) in listData" :key="index" class="scroll-view-item">
        <slot name="item" :item="item" :index="index"></slot>
      </view>
      <view v-if="loading" class="text-center">加载中</view>
      <VEmpty v-else-if="total === 0 || isBusinessError" style="height: 100%" />
      <view v-else-if="total === (listData || []).length" class="text-center">到底了</view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
.scroll-list-view {
  height: 100%;

  .text-center {
    line-height: 80px;
    color: rgba(0, 0, 0, 0.7);
    text-align: center;
  }
}
</style>
